<script setup lang="ts">
import type { PunchRecordRespVO } from '@/api/types/punch'
import { nextTick } from 'vue'

interface Props {
  visible: boolean
  punchData?: PunchRecordRespVO
  userInfo?: { avatar?: string, nickname?: string }
}

interface Emits {
  (e: 'generated', imageUrl: string): void
  (e: 'error', error: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
})

const emit = defineEmits<Emits>()

// Canvas配置
const canvasWidth = 375
const canvasHeight = 500
const canvasId = 'shareCanvas'

// 生成分享卡片
async function generateShareCard() {
  if (!props.punchData)
    return

  try {
    await nextTick()

    const ctx = uni.createCanvasContext(canvasId)

    // 1. 绘制背景渐变
    const gradient = ctx.createLinearGradient(0, 0, 0, canvasHeight)
    gradient.addColorStop(0, '#f0f9ff')
    gradient.addColorStop(0.5, '#e0f2fe')
    gradient.addColorStop(1, '#bae6fd')

    ctx.setFillStyle(gradient)
    ctx.fillRect(0, 0, canvasWidth, canvasHeight)

    // 2. 绘制主卡片背景
    const cardPadding = 20
    const cardX = cardPadding
    const cardY = cardPadding
    const cardWidth = canvasWidth - cardPadding * 2
    const cardHeight = canvasHeight - cardPadding * 2

    ctx.setFillStyle('#ffffff')
    ctx.setShadow(0, 5, 15, 'rgba(0, 0, 0, 0.1)')
    drawRoundedRect(ctx, cardX, cardY, cardWidth, cardHeight, 16)
    ctx.fill()
    ctx.setShadow(0, 0, 0, 'transparent')

    // 3. 绘制头部信息
    let currentY = cardY + 40

    // 用户昵称
    ctx.setFillStyle('#1e293b')
    ctx.setFontSize(18)
    ctx.setTextAlign('left')
    ctx.fillText(props.userInfo?.nickname || '小读者', cardX + 20, currentY)

    // 打卡日期
    ctx.setFillStyle('#94a3b8')
    ctx.setFontSize(14)
    const dateText = formatShareDate(props.punchData.punchDate)
    ctx.fillText(dateText, cardX + 20, currentY + 25)

    currentY += 70

    // 4. 绘制阅读统计
    const statsY = currentY
    const statWidth = (cardWidth - 40) / 3

    // 统计背景
    ctx.setFillStyle('#f8fafc')
    drawRoundedRect(ctx, cardX + 20, statsY, cardWidth - 40, 80, 12)
    ctx.fill()

    // 统计数据
    const stats = [
      { label: '本绘本', value: props.punchData.bookCount.toString() },
      { label: '连续天', value: props.punchData.dayCount.toString() },
      { label: '已打卡', value: '✓' },
    ]

    stats.forEach((stat, index) => {
      const statX = cardX + 20 + index * statWidth + statWidth / 2

      // 数值
      ctx.setFillStyle('#42bbff')
      ctx.setFontSize(24)
      ctx.setTextAlign('center')
      ctx.fillText(stat.value, statX, statsY + 35)

      // 标签
      ctx.setFillStyle('#94a3b8')
      ctx.setFontSize(12)
      ctx.fillText(stat.label, statX, statsY + 55)
    })

    ctx.setTextAlign('left')
    currentY = statsY + 100

    // 5. 绘制打卡心得
    if (props.punchData.commentText) {
      ctx.setFillStyle('#1e293b')
      ctx.setFontSize(16)

      const commentText = props.punchData.commentText.length > 40
        ? `${props.punchData.commentText.substring(0, 40)}...`
        : props.punchData.commentText

      ctx.fillText(`"${commentText}"`, cardX + 20, currentY)
      currentY += 60
    }

    // 6. 绘制底部信息
    const bottomY = cardY + cardHeight - 60

    ctx.setFillStyle('#94a3b8')
    ctx.setFontSize(12)
    ctx.setTextAlign('center')
    ctx.fillText('一起来阅读绘本吧！', canvasWidth / 2, bottomY)

    ctx.setFillStyle('#42bbff')
    ctx.setFontSize(16)
    ctx.fillText('绘本阅读小程序', canvasWidth / 2, bottomY + 25)

    // 绘制到Canvas
    ctx.draw(false, () => {
      // 导出图片
      uni.canvasToTempFilePath({
        canvasId,
        fileType: 'png',
        quality: 0.8,
        success: (res) => {
          emit('generated', res.tempFilePath)
        },
        fail: (error) => {
          console.error('导出Canvas图片失败:', error)
          emit('error', error)
        },
      })
    })
  }
  catch (error) {
    console.error('生成分享卡片失败:', error)
    emit('error', error)
  }
}

// 绘制圆角矩形
function drawRoundedRect(ctx: any, x: number, y: number, width: number, height: number, radius: number) {
  ctx.beginPath()
  ctx.moveTo(x + radius, y)
  ctx.lineTo(x + width - radius, y)
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius)
  ctx.lineTo(x + width, y + height - radius)
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height)
  ctx.lineTo(x + radius, y + height)
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius)
  ctx.lineTo(x, y + radius)
  ctx.quadraticCurveTo(x, y, x + radius, y)
  ctx.closePath()
}

// 格式化分享日期
function formatShareDate(dateStr: string): string {
  const date = new Date(dateStr)
  const today = new Date()

  if (date.toDateString() === today.toDateString()) {
    return '今天打卡'
  }

  return `${date.getMonth() + 1}月${date.getDate()}日打卡`
}

// 暴露生成方法
defineExpose({
  generateShareCard,
})
</script>

<template>
  <view v-if="visible" class="share-canvas-container">
    <canvas
      canvas-id="shareCanvas"
      :style="{ width: `${canvasWidth}px`, height: `${canvasHeight}px` }"
      class="share-canvas"
    />
  </view>
</template>

<style lang="scss" scoped>
.share-canvas-container {
  position: fixed;
  top: -9999px;
  left: -9999px;
  z-index: -1;
  opacity: 0;
}

.share-canvas {
  background-color: transparent;
}
</style>
